package com.hogocloud.corelibrary.http

import com.hogocloud.corelibrary.base.OptionT
import com.hogocloud.corelibrary.utils.NetWorkUtils
import com.hogocloud.corelibrary.utils.ToastUtils
import io.reactivex.observers.DisposableObserver

/**
 * 统一的订阅类
 *
 * @author gjc
 * @version 1.0.0
 * @since 2018-10-09
 */

class CommonSubscriber<T> constructor(private val requestCallback: RequestCallback<T>?) :
    DisposableObserver<OptionT<T>>()  {

    companion object{
        private const val TAG = "common_subscriber"
    }

    override fun onStart() {
        super.onStart()
        if (!NetWorkUtils.isNetworkConnected()) {
            ToastUtils.showToast("当前网络不可用，请检查网络！")
            //手动取消本次订阅
            if (!isDisposed) {
                dispose()
            }
        }
    }

    override fun onNext(t: OptionT<T>) {
        requestCallback?.onSuccess(t.value)
    }

    override fun onError(e: Throwable) {
        if (requestCallback == null) {
            return
        }
        val message = e.message
        val msg = if (message.isNullOrBlank()) "未知错误" else message
        when (requestCallback) {
            is RequestMultiplyToastCallback -> {
                ToastUtils.showToast(msg = msg)
                if (e is BaseException) {
                    requestCallback.onFail(e)
                } else {
                    requestCallback.onFail(ServerResultException(message = msg))
                }
            }
            is RequestMultiplyCallback -> {
                if (e is BaseException) {
                    requestCallback.onFail(e)
                } else {
                    requestCallback.onFail(ServerResultException(message = msg))
                }
            }
            else -> {
                ToastUtils.showToast(msg = msg)
            }
        }
    }

    override fun onComplete() {

    }

}
